package dto;

public abstract class GSTDAccount {
	private int balance;
	private PropertyField[] properties;

	public GSTDAccount(int balance) {
		addBalance(balance);
		properties = new PropertyField[0];
	}

	public void addBalance(int amount) {
		this.balance += Math.abs(amount);
	}

	public void subBalance(int amount) {
		amount = Math.abs(amount);
		balance = balance - amount < 0 ? 0 : balance - amount;
	}

	public boolean hasAfford(int amount) {
		return balance - amount >= 0;
	}

	public int getBalance() {
		return balance;
	}

	public void addProperty(PropertyField property) {
		PropertyField[] newProperties = new PropertyField[properties.length + 1];
		newProperties[newProperties.length - 1] = property;
		for (int i = 0; i < properties.length; i++) {
			newProperties[i] = properties[i];
		}
		properties = newProperties;
	}

	public void removeProperty(PropertyField property) {
		boolean propertyCheck = false;
		for (int i = 0; i < properties.length; i++) {
			if (properties[i] == property) {
				propertyCheck = true;
				break;
			}
		}
		if (!propertyCheck)
			System.out.println("Error. Property was not found!");

		PropertyField[] newProperties = new PropertyField[properties.length - 1];
		int c = 0;
		for (int i = 0; i < properties.length; i++) {
			if (properties[i] != property) {
				newProperties[c] = properties[i];
				c++;
			}
		}
		properties = newProperties;
	}

	public PropertyField[] getProperties() {
		return properties;
	}

	public int getNumberOfFields(Class<? extends PropertyField> classProp) {
		int i = 0;
		for (int p = 0; p < properties.length; p++) {
			if (properties[p].getClass() == classProp) {
				i++;
			}
		}
		return i;
	}

	public int getTotalAssets() {
		int totalAssets = balance;

		for (int p = 0; p < properties.length; p++) {
			totalAssets += properties[p].getPrice();
		}

		return totalAssets;
	}

	public void resetAll() {
		balance = 0;
		properties = new PropertyField[0];
		reset();
	}

	abstract protected void reset();
}
